package com.mall.web.control.weishang;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.mall.biz.user.UserBizImpl;
import com.mall.biz.user.VerifyCodeBizImpl;
import com.mall.biz.weishang.WeishangUserBizImpl;
import com.mall.client.commkey.CommKeyService;
import com.mall.client.region.AreaService;
import com.mall.client.region.CityService;
import com.mall.client.region.ProvinceService;
import com.mall.client.user.AddressService;
import com.mall.client.user.UserExtendedService;
import com.mall.client.user.UserService;
import com.mall.common.Consts.PassJiaMi;
import com.mall.common.util.IDCardUtil;
import com.mall.common.util.MD5Util;
import com.mall.common.util.bit.PropertiesConfigure;
import com.mall.common.util.token.TokenUtils;
import com.mall.constant.PropertiesKey;
import com.mall.constant.ReqAttributeKey;
import com.mall.constant.UserConstant;
import com.mall.enums.AddressEnum;
import com.mall.pojo.Address;
import com.mall.pojo.Area;
import com.mall.pojo.City;
import com.mall.pojo.Commkey;
import com.mall.pojo.Province;
import com.mall.pojo.User;
import com.mall.pojo.UserExtended;
import com.mall.vo.user.AliTonghua;
import com.mall.vo.user.UserVO;
import com.mall.web.annotation.MaidianSecurity;
import com.mall.web.util.AliBaiChuanUtil;
import com.mall.web.util.HttpUtil;
import com.mall.web.util.WebUtil;
import com.mall.web.vo.ResponseEntity;
import com.mall.web.vo.StatusInfo;
/**
 * 合伙人系统用户信息操作
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/maidian/user/")
public class WeishangUserController {
	private Logger log = LoggerFactory.getLogger(WeishangUserController.class);
	@Autowired
	private UserService userService;
	@Autowired
	private VerifyCodeBizImpl verifyCodeBiz;
	@Autowired
	private UserBizImpl userBiz;
	@Autowired
	private PropertiesConfigure propertiesConfigure;
	@Autowired
	private WeishangUserBizImpl weishangUserBizImpl;
	@Autowired
	private AddressService addressService;
	@Autowired
	private UserExtendedService userExtendedService;
	@Autowired
	private ProvinceService provinceService;
	@Autowired
	private CityService cityService;
	@Autowired
	private AreaService areaService;
	@Autowired
	private CommKeyService comKeyService;
	
	private final String USERPNG = "weishang/morenHead.png";
	/**
	 * 用户注册
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@RequestMapping("register")
	public String register(HttpServletRequest request,HttpServletResponse response,ModelMap modelMap){
		return "weishang/user/register";
	}
	/**
	 * 校验验证码是否正确
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@RequestMapping("toBasicInfo")
	public ResponseEntity<String> toBasicInfo(HttpServletRequest request,HttpServletResponse response,ModelMap modelMap){
		ResponseEntity<String> responseEntity = new ResponseEntity<>();
		String verifyCode = HttpUtil.getStringValueFromRequest(request, "verifyCode");
		String phone = HttpUtil.getStringValueFromRequest(request, "phone");
		boolean isVerifyCode = verifyCodeBiz.checkVerifyCode(phone, verifyCode);
		if(isVerifyCode){
			responseEntity.setCode("200");
			responseEntity.setData(null);
			responseEntity.setMessage("验证通过");
			return responseEntity;
		}
		responseEntity.setCode("-200");
		responseEntity.setData(null);
		responseEntity.setMessage("验证不通过");
		return responseEntity;
	}
	/**
	 * 跳转注册填写基本信息页面
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@RequestMapping("basicInfo")
	public String basicInfo(HttpServletRequest request,HttpServletResponse response,ModelMap modelMap){
		String phone = HttpUtil.getStringValueFromRequest(request, "phone");
		modelMap.put("phone", phone);
		return "weishang/user/basicInfo";
	}
	@RequestMapping("registerAction")
	@Transactional
	public ResponseEntity<UserVO> registerAction(HttpServletRequest request,HttpServletResponse response,ModelMap modelMap){
		ResponseEntity<UserVO> responseEntity = new ResponseEntity<>();
		
		Integer onlyKey = HttpUtil.getCommkeyId(request, response);
		String phone = request.getParameter("phone") == null ? "" : request.getParameter("phone").trim();
		
		if (StringUtils.isBlank(phone)) {
			responseEntity.setCode("-200");
			responseEntity.setData(null);
			responseEntity.setMessage("手机号为空");
			return responseEntity;
		}
		
		String idCard = HttpUtil.getStringValueFromRequest(request, "idCard");
		if(!IDCardUtil.isValidatedAllIdcard(idCard)){
			responseEntity.setCode("-800");
			responseEntity.setData(null);
			responseEntity.setMessage("请填写正确的身份证信息");
			return responseEntity;
		}
		
		User userPhone = this.userService.getUserByPhone(phone, onlyKey);// 校验手机号是否注册过
		if (userPhone != null) {
			responseEntity.setCode("-300");
			responseEntity.setData(null);
			responseEntity.setMessage("phone  is used");
			return responseEntity;
		}
		
		String userName = HttpUtil.getStringValueFromRequest(request, "userName");
		String password = HttpUtil.getStringValueFromRequest(request, "password");
		Integer provinceId = HttpUtil.getIntegerValueFromRequest(request, "provinceId");
		Integer cityId = HttpUtil.getIntegerValueFromRequest(request, "cityId");
		Integer areaId = HttpUtil.getIntegerValueFromRequest(request, "areaId");
		String address = HttpUtil.getStringValueFromRequest(request, "address");
		
		
		
		UserVO userVO = new UserVO();
		Date createTime = new Date();
		User user = new User();
		user.setCommOnlyKey(onlyKey);
		user.setPassword(getPassWordMd5(password, phone));// 注册时密码不需要校验吗？还需要md5加密
		user.setPortrait(USERPNG);
		user.setPhone(phone);
		user.setUserName(userName);
		user.setNameAndPhone(userName + phone);
		user.setIdCard(idCard);
		
		userVO.setUser(user);
		/**
		 * 用户阿里百川存入数据库
		 */
		String deviceToken = request.getParameter("deviceToken");// 手机对应型号
		String aliUserId = AliBaiChuanUtil.UID + phone;
		String aliPass = AliBaiChuanUtil.PASS;
		AliTonghua aliTonghua = new AliTonghua(aliUserId, aliPass);
		UserExtended userExtended = new UserExtended();
		userExtended.setAliTongxun(JSONArray.toJSONString(aliTonghua));
		userExtended.setAliTongxueId(aliUserId);
		userExtended.setDeviceToken(deviceToken);
		userVO.setUserExtended(userExtended);
		
		
		int isRegister = this.weishangUserBizImpl.weishangRegister(userVO, createTime);
		if(isRegister <= 0){
			responseEntity.setCode("-600");
			responseEntity.setData(null);
			responseEntity.setMessage("插入数据库失败，请重试");
			return responseEntity;
		}
		
		Address userAddress = new Address();
		Province province = this.provinceService.getProvinceById(provinceId);
		City city = this.cityService.getCityById(cityId);
		Area area = this.areaService.getAreaByAreaId(areaId);
		userAddress.setAddress(province.getProvinceName()+city.getCityName()+area.getAreaName()+address);
		userAddress.setAreaId(areaId);
		userAddress.setCityId(cityId);
		userAddress.setProvinceId(provinceId);
		userAddress.setCommOnlyKey(onlyKey);
		userAddress.setGmtCreate(createTime);
		userAddress.setGmtModify(createTime);
		userAddress.setName(userName);
		userAddress.setPhone(phone);
		userAddress.setUserId(userVO.getUser().getId());
		userAddress.setType(0);
		userAddress.setAttribute(province.getProvinceName()+" "+city.getCityName()+" "+area.getAreaName());
		userAddress.setStatus(AddressEnum.DEFAULTADDRESS.getCode());
		int isInsertAddress = this.addressService.insertAddress(userAddress);
		if(isInsertAddress <= 0){
			responseEntity.setCode("-600");
			responseEntity.setData(null);
			responseEntity.setMessage("插入数据库失败，请重试");
			return responseEntity;
		}
		/**
		 * 用户注册到阿里百川
		 */
		boolean insertResult = AliBaiChuanUtil.insertUserInfoAliBaiChuan(user);
		log.error("插入用户到阿里百川" + insertResult);

		Boolean sessResult = userBiz.updateOrInsertSess(request, response, userVO, onlyKey);
		log.info("更新session", sessResult);
		if (!sessResult) {
			responseEntity.setCode("-500");
			responseEntity.setData(null);
			responseEntity.setMessage("sess insert or update error");
			return responseEntity;
		}
		
		String userImgUrl = propertiesConfigure.getProperties(PropertiesKey.userfilepath);
		userVO.setImgBeiginUrl(userImgUrl);
		String token = TokenUtils.getToken(userVO.getUser().getId(), user.getPassword(), new Date());
		userVO.setToken(token);
		userVO.setSessionID(WebUtil.getUserCookieValue(request));
		responseEntity.initSuccResponseEntity(userVO, "注册成功");
		return responseEntity;
	}
	
	private String getPassWordMd5(String passWord, String phone) {
		return MD5Util.GetMD5Code(passWord, phone + "", PassJiaMi.MD5JIAYAN);
	}
	
	
	@RequestMapping("registerSuccess")
	public String registerSuccess(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap){
		return "weishang/user/registerSuccess";
	}
	
	
	/**
	 * 用户登录
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@RequestMapping("login")
	public String login(HttpServletRequest request,HttpServletResponse response,ModelMap modelMap){
//		Integer onlyKey = HttpUtil.getCommkeyId(request, response);
		Integer onlyKey = HttpUtil.getIntegerValueFromRequest(request, ReqAttributeKey.COOKIE_FOR_COMMKEYID);
		if (onlyKey ==null) {
			onlyKey = HttpUtil.getCommkeyId(request, response);
		}
		List<Commkey> comKeyList = this.comKeyService.getComKeyByCommOnlyKey(onlyKey);
		Commkey commkey = null;
		if (comKeyList != null && comKeyList.size()>0) {
			commkey = comKeyList.get(0);
		}
		modelMap.put("commkey", commkey);
		return "weishang/user/login";
	}
	@RequestMapping("loginAction")
	public ResponseEntity<UserVO> loginAction(HttpServletRequest request,HttpServletResponse response,ModelMap modelMap){
		Integer onlyKey = HttpUtil.getCommkeyId(request, response);
		String deviceToken = request.getParameter("deviceToken");
		ResponseEntity<UserVO> responseEntity = new ResponseEntity<>();

		UserVO userVO = this.userBiz.login(request.getParameter("phone"), request.getParameter("password"),
				onlyKey);// 用户手机号登陆
		if (userVO == null) {
			responseEntity.initErrorResponseEntity(null, "账号或密码错误");
			return responseEntity;
		}
		UserExtended userExtended = this.userExtendedService.getUserExtendByUserId(userVO.getUser().getId());
		String userDeviceToken = null;
		if(userExtended != null){
			userDeviceToken = userExtended.getDeviceToken();
		}
		
		if (StringUtils.isNotBlank(userDeviceToken) && StringUtils.isNotBlank(deviceToken)) {
			if (!userDeviceToken.equals(deviceToken)) {// deviceToken不同时候更新
				userVO.setUserExtended(userExtended);
				/**
				 * 用户登陆更新app对应的deviceToken
				 */
				Boolean updateyoumengDeviceToken = this.userBiz.updateDeviceToken(userVO,
						request.getParameter("deviceToken"));
				log.info("更新deviceToken", updateyoumengDeviceToken);
			}
		}

		Boolean sessResult = userBiz.updateOrInsertSess(request, response, userVO, onlyKey);
		log.info("更新session", sessResult);
		if (!sessResult) {
			responseEntity.setCode("-300");
			responseEntity.setData(null);
			responseEntity.setMessage("sess insert or update error");
			return responseEntity;
		}
		responseEntity.initSuccResponseEntity(userVO, "login success");
		return responseEntity;
	}
	
	
	/**
	 * 检测手机号是否注册过
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@RequestMapping("checkPhone")
	@ResponseBody
	public ResponseEntity<UserVO> checkPhone(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
		Integer onlyKey = HttpUtil.getCommkeyId(request, response);
		String phone = request.getParameter("phone");
		ResponseEntity<UserVO> responseEntity = new ResponseEntity<>();
		User user = this.userService.getUserByPhone(phone, onlyKey);
		if (user != null) {
			responseEntity.setCode("-200");
			responseEntity.setData(null);
			responseEntity.setMessage("phone is used");
			return responseEntity;
		}
		responseEntity.setCode("200");
		responseEntity.setData(null);
		responseEntity.setMessage("phone can use");
		return responseEntity;
	}
	
	
	
	
	
	@RequestMapping("sendVerifyCode")
	public String sendVerifyCode(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap){
		String phone = HttpUtil.getStringValueFromRequest(request, "phone");
		modelMap.put("phone", phone);
		return "weishang/user/sendVerifyCode";
	}
	
	/**
	 * 发送验证码
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@RequestMapping("sendVerifyCodeAction")
	@ResponseBody
	public ResponseEntity<String> sendVerifyCodeAction(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
		try {
			String phone = request.getParameter("phone").trim();
			String sourseType = request.getParameter("sourseType");// f:忘记密码 r：注册
			Integer onlyKey = HttpUtil.getCommkeyId(request, response);
			
			if (StringUtils.isBlank(phone)) {
				ResponseEntity<String> responseEntity = new ResponseEntity<String>("-400","手机号为空", null);
				return responseEntity;
			}
			
			//忘记密码时却未注册
			if ("f".equalsIgnoreCase(sourseType)) {
				User user = this.userService.getUserByPhone(phone,onlyKey);
				if (user == null) {
					ResponseEntity<String> responseEntity = new ResponseEntity<String>("-500","手机号码尚未注册", null);
					return responseEntity;
				}
			}
			
			//注册时已经注册，该项目可删减
			if ("r".equalsIgnoreCase(sourseType)) {
				User user = this.userService.getUserByPhone(phone,onlyKey);
				if (user != null) {
					ResponseEntity<String> responseEntity = new ResponseEntity<String>("-600","手机号码已注册", null);
					return responseEntity;
				}
			}
			
			//发送验证码
			String result = verifyCodeBiz.sendVerifyCode(phone);
			if (StringUtils.isEmpty(result)) {
				ResponseEntity<String> responseEntity = new ResponseEntity<String>(StatusInfo.REQUEST_FAILURE,
						StatusInfo.REQUEST_FAILURE_MSG, null);
				return responseEntity;
			}
			
			if ("sendmsg error".equals(result)) {
				ResponseEntity<String> responseEntity = new ResponseEntity<String>("-201", "号码发送过于频发", null);
				return responseEntity;
			}
			ResponseEntity<String> responseEntity = new ResponseEntity<String>(StatusInfo.REQUEST_SUCCESS,
					StatusInfo.REQUEST_SUCCESS_MSG, result);
			return responseEntity;
		} catch (Exception e) {
			ResponseEntity<String> responseEntity = new ResponseEntity<String>(StatusInfo.REQUEST_FAILURE,
					StatusInfo.REQUEST_FAILURE_MSG, null);
			return responseEntity;
		}
	}
	
	/**
	 * 忘记密码
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return5
	 */
	@RequestMapping("forgetPassword")
	public String forgetPassword(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap){
		return "weishang/user/forgetPassword";
	}
	@RequestMapping("forgetPasswordAction")
	public ResponseEntity<UserVO> forgetPasswordAction(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap){
		String verifyCode = HttpUtil.getStringValueFromRequest(request, "verifyCode");
		String password = HttpUtil.getStringValueFromRequest(request, "password");
		String phone = HttpUtil.getStringValueFromRequest(request, "phone");
		Integer onlyKey = HttpUtil.getCommkeyId(request, response);
		
		ResponseEntity<UserVO> responseEntity = new ResponseEntity<UserVO>();
		
		if (StringUtils.isBlank(phone) || StringUtils.isBlank(verifyCode) || StringUtils.isBlank(password)) {
			responseEntity.setCode("-100");
			responseEntity.setData(null);
			responseEntity.setMessage("请填写完整各项信息");
			return responseEntity;
		}

		User user = this.userService.getUserByPhone(phone, onlyKey);
		if (user == null) {// 用户不存在，提醒去注册
			responseEntity.setCode("-300");
			responseEntity.setData(null);
			responseEntity.setMessage("用户未注册，请注册");
			return responseEntity;
		}
		boolean isVerifyCode = verifyCodeBiz.checkVerifyCode(phone, verifyCode);
		if (isVerifyCode == false) {
			responseEntity.setCode("-400");
			responseEntity.setData(null);
			responseEntity.setMessage("输入的邀请码错误");
			return responseEntity;
		}

		user.setGmtModify(new Date());
		user.setPassword(getPassWordMd5(password, user.getPhone()));// 忘记密码时候设置新密码
		this.userService.modifytUserByPrimaryKey(user);
		UserVO userVO = new UserVO();
		userVO.setUser(user);
		Boolean sessResult = this.userBiz.updateOrInsertSess(request, response, userVO, onlyKey);
		log.info("更新session", sessResult);

		responseEntity.initSuccResponseEntity(userVO, "set pass success");
		return responseEntity;
	}

	@RequestMapping("index")
	@MaidianSecurity
	public String userIndex(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap){
		User user = WebUtil.getCurrentUser(request);
		if(user.getType() == UserConstant.TYPE_MANAGE){
			return "redirect:/maidian/supplier/supplierIndex.htm";
		}
		return "redirect:/maidian/distributor/distributorItemList.htm";
	}
	
	

}
